package session

import (
	"sync"
	"video/api/dbops"
	"video/api/defs"
	"github.com/satori/go.uuid"
	"time"
)

var sessionMap *sync.Map

func init() {
	sessionMap = &sync.Map{}
}

func LoadFromDB() {
	sessions, _ := dbops.RetrieveAllSession()
	sessions.Range(func(k, v interface{}) bool {
		sessionMap.Store(k, v.(*defs.Session))
		return true
	})
}

func GenerateNewSessionId(un string) {
	//uuid
	u1, _ := uuid.NewV4()
	uuidString := u1.String()
	millisNow := time.Now().UnixNano() / 1000000
	ttl := millisNow + 30*60*1000
	ss := defs.Session{
		Id:        uuidString,
		TTL:       ttl,
		LoginName: un,
	}
	sessionMap.Store(uuidString, ss)
	dbops.InsertSession(uuidString, ttl, un)
}

func IsSessionExpired(sid string) (string, bool) {
	value, _ := sessionMap.Load(sid)
	if value == nil {
		return "", true
	}
	ss := value.(*defs.Session)
	if ss.TTL < time.Now().UnixNano()/1000000 {
		return "", true
	}
	return ss.LoginName, false
}

func DeleteSession(sid string) {
	sessionMap.Delete(sid)
	dbops.DeleteSession(sid)
}
